package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import io.lettuce.core.RedisClient;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 钟乐
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    //@Cacheable(value = "cache:shop:", key="#id")
    @Override
    public Result queryById(Long id) {

//工具类解决缓存击穿
//        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,this::getById,5L,TimeUnit.MINUTES);

        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("商铺不存在");
        }

        return Result.ok(shop);

    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {

        //1是否需要根据坐标查询
        if(x==null||y==null){

            //按数据库查询,使用mybatis自带的分页查询,给第几页，。每页的pageSize就好了。
            Page<Shop> page = query()
                .eq("type_id", typeId)
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));

            return Result.ok(page.getRecords());

        }

        //计算分页参数，current是页码，
        int from = (current - 1 ) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        String key = "shop:geo:" + typeId;

        //查询redis,按照距离排序，分页， stringRedisTemplate.opsForGeo().search
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo()
                .search(key,  //key
                        GeoReference.fromCoordinate(x, y), //point
                        new Distance(5000),  //distance
                        //查询结果带上距离
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));

        //判空
        if (geoResults==null){
            return Result.ok(Collections.emptyList());
        }

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = geoResults.getContent();
        //解析出id,根据id查询shop结果

        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceMap = new HashMap<>(list.size());

        //截取from-end,使用stream流
        list.stream().skip(from).forEach(result->{

            //查询店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));

            //查询店铺距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr,distance);
        });

        //跳过之后查询可能为空
        if(list.size() <= from ){
            //跳过的数量比集合的size还大就没数据了
            return Result.ok();
        }

        //查询店铺信息
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        for (Shop shop : shops) {

            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());  //getValue转为double
        }

        return Result.ok(shops);
    }

    //缓存击穿+缓存穿透解决方案
    private Shop queryWithMutex(Long id){

        String key = "cache:shop:" + id;

        String shopJson = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(shopJson)) {
            //拿到字符，转为Shop.class，JSONUtil

            return JSONUtil.toBean(shopJson, Shop.class);
        }

        //剩下的就只有null和'',当命中''时,redis里面有这个键，是''，解决缓存穿透问题
        if(shopJson!=null){
            return null;
        }

        //缓存里即没有''，也没有值，需要解决缓存击穿问题
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try{
            Boolean isLock = tryLock(lockKey);
            if (!isLock){
                Thread.sleep(50);
                return queryWithMutex(id);  //没拿到锁，重试，查缓存，再尝试拿锁，用递归实现的
            }

            //redis里面都没有这个键，返回null，就要查数据库了
            shop = getById(id);

            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key,"",2, TimeUnit.MINUTES);
                return null;
            }

            //将shop类转为字符存入redis,ttl后面添加随机时间解决线程雪崩
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),30+(int)(Math.random()*30), TimeUnit.MINUTES);

        }catch(InterruptedException e)
        { throw new RuntimeException();}
        finally {
            deleteLock(lockKey);
        }
        return shop;

    }

    //缓存穿透解决方案
//    private Shop queryWithPassThrough(Long id){
//
//        String key = "cache:shop:" + id;
//
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//
//        if (StrUtil.isNotBlank(shopJson)) {
//            //拿到字符，转为Shop.class，JSONUtil
//
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//
//        //剩下的就只有null和'',当命中''时,redis里面有这个键，是''，解决缓存穿透问题
//        if(shopJson!=null){
//            return null;
//        }
//
//        //缓存里即没有''，也没有值，需要解决缓存击穿问题
//        String lockKey = "lock:shop:" + id;
//        Shop shop = null;
//
//        //redis里面都没有这个键，返回null，就要查数据库了
//        shop = getById(id);
//
//        if (shop == null) {
//            stringRedisTemplate.opsForValue().set(key,"",2, TimeUnit.MINUTES);
//            return null;
//        }
//
//        //将shop类转为字符存入redis,ttl后面添加随机时间解决线程雪崩
//        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),30+(int)(Math.random()*30), TimeUnit.MINUTES);
//
//
//        return shop;
//
//    }


    private Boolean tryLock(String key){
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(key, "lock",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(lock);  //自动拆箱可能造成空指针
    }

    private void deleteLock(String key){
        stringRedisTemplate.delete(key);
    }


}
